package com.ken.astroboy.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Scanner;

public class FileUtil {

    public static void write(String path, String content, String encoding, boolean append) throws IOException {  
        File file = new File(path); 
        BufferedWriter writer = null;
        
        File dir = file.getParentFile(); 
        
	    if(dir != null){
		    if (!dir.exists()) {  
		        dir.mkdirs();  
		    }	    	
	    } 
        
        if(file.exists()){
            writer = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(file, append), encoding) );         
        }else{
            file.createNewFile(); 
            writer = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(file), encoding) );                   
        }
        writer.write(content);  
        writer.close();  
    }  
  
    public static String read(String path, String encoding) throws IOException {  
        String content = "";  
        File file = new File(path); 
        if(file.exists()){
	        BufferedReader reader = new BufferedReader(new InputStreamReader( new FileInputStream(file), encoding));  
	        String line = null;  
	        while ((line = reader.readLine()) != null) {  
	        	content += line;
	        }  
	        reader.close();  
	        return content;  	
        }else{
        	return null;
        }
    }  
    
    //与read()读出来内容是一样的。
	@SuppressWarnings("resource")
	public static String readWithScanner(String path, String encoding) throws FileNotFoundException{  

        File file = new File(path); 
        if(file.exists()){
        	Scanner scanner = null;
    		StringBuilder buffer = new StringBuilder();
    		
    		scanner = new Scanner(file, encoding);
    		while (scanner.hasNextLine()) {
    			buffer.append(scanner.nextLine());
    		}
    		
    		return buffer.toString();
        }else{
        	return null;
        }
    }  		
}
